const express = require("express");
const http = require("http");
let { Server } = require("socket.io");
const fs = require("fs").promises;
const multer = require('multer')
let dest = "download";

const storage = multer.memoryStorage()
const upload = multer({ storage })

let app = express()
app.post("/upload", upload.any(), async (req, res) => {
    req.files.forEach(async el => {
        let originalname = Buffer.from(el.originalname, "latin1").toString(
            "utf8"
        );
        let filePath = `${dest}/${originalname}`;
        await fs.writeFile(filePath, el.buffer)
        syncEmit(socks, "download", dest, originalname)
        setTimeout(() => {
            require("fs").unlinkSync(filePath)
        }, 1 * 1000 * 60)
    })
})
let server = http.createServer(app);

let io = new Server(server, {
    cors: true
});

let message = "";
let socks = [];
syncEmit = (socks, key, ...value) => {
    socks.forEach(sock => {
        sock.emit(key, ...value);
    })
}


io.on("connection", socket => {
    socks.push(socket);
    socket.emit("sync_msg", message);
    syncEmit(socks, "sync_count", socks.length);
    socket.on("send_msg", str => {
        message = str;
        if (/^\[(.+)?\]$/.test(message)) {
            syncEmit(socks.filter(sock => sock != socket), "open_url", RegExp.$1);
        } else {

        }
        syncEmit(socks.filter(sock => sock != socket), "sync_msg", message);
    });
    socket.on("disconnect", () => {
        socks = socks.filter(sock => sock != socket);
        syncEmit(socks, "sync_count", socks.length);
    });
});



server.listen(port = process.env[2] || 1314, () => {
    console.log(`server running at localhost:${port}`);
});

app.use("*", (req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Headers", "*");
    next();
})

app.get(`/${dest}/:filename`, (req, res) => {
    let { filename } = req.params;
    res.download(`./${dest}/${filename}`, (err) => {
        if (err) res.send(404);
    });
})

app.use(express.static("./www"));
